﻿using System.Text;
using YMJake.Flowable.ExternalWorker.Client.AspNetCore.Pipeline;
using YMJake.Flowable.ExternalWorker.Client.Core.Client;

namespace YMJake.Flowable.ExternalWorker.Client.Sample.Handlers;

/// <summary>
/// 异步处理器
/// </summary>
public class AsyncProcessHandler : IWorkerHandler
{
    private readonly ILogger<AsyncProcessHandler> _logger;

    public AsyncProcessHandler(ILogger<AsyncProcessHandler> logger)
    {
        _logger = logger;
    }

    public async Task HandleAsync(IWorkerPipelineContext context)
    {
        _logger.LogInformation("Starting async processing for job {JobId}", context.Job.Id);

        try
        {
            await Task.Delay(2000, context.CancellationToken);

            var data = GetStringVariable(context.Job, "data");
            
            var bytes = Encoding.UTF8.GetBytes(data);
            _logger.LogDebug("Data bytes: {Bytes}", Convert.ToHexString(bytes));
            
            _logger.LogInformation("Processed data: {Data}", data);
            Console.WriteLine($"Console output - Processed data: {data}");

            context.Result = context.ResultBuilder.Success()
                .Variable("processedData", data)
                .Variable("processedAt", DateTime.UtcNow);
        }
        catch (Exception ex)
        {
            context.Result = context.ResultBuilder.Failure()
                .Error(ex);
        }
    }

    private string GetStringVariable(IAcquiredExternalWorkerJob job, string key, string defaultValue = "")
    {
        var value = job.Variables.GetValueOrDefault(key, defaultValue);
        return value?.ToString() ?? defaultValue;
    }
}